/*
 * @Author: Await
 * @Date: 2025-04-24 15:50:26
 * @LastEditors: Await
 * @LastEditTime: 2025-04-30 16:59:26
 * @Description: 请填写简介
 */
/*
 * @Author: Await
 * @Date: 2025-04-23 11:45:30
 * @LastEditors: Await
 * @LastEditTime: 2025-04-23 11:45:30
 * @Description: 标记线配置组件
 */
import React, { useState, useOptimistic } from 'react';
import {
    Form,
    Input,
    Switch,
    Select,
    InputNumber,
    Row,
    Col,
    Typography,
    Tooltip,
    ColorPicker,
    Button,
    Table,
    Divider,
    Space,
    Modal
} from 'antd';
import { InfoCircleOutlined, PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { useActionState } from 'react';  // 单独导入React 19的useActionState

// 标记线点位
export interface MarkLinePoint {
    type?: 'min' | 'max' | 'average' | '';
    name?: string;
    xAxis?: number | string;
    yAxis?: number | string;
    value?: number;
    symbol?: string;
    symbolSize?: number;
}

// 标记线类型
export interface MarkLineItem {
    type?: 'min' | 'max' | 'average' | '';
    name?: string;
    xAxis?: number | string;
    yAxis?: number | string;
    x?: number | string;
    y?: number | string;
    valueIndex?: 0 | 1;
    valueDim?: string;
    coord?: [number | string, number | string];
    // 起点和终点，用于自定义起止位置的标记线
    startPoint?: MarkLinePoint;
    endPoint?: MarkLinePoint;
    // 线条样式
    lineStyle?: {
        color?: string;
        width?: number;
        type?: 'solid' | 'dashed' | 'dotted';
        opacity?: number;
    };
    label?: {
        show?: boolean;
        position?: 'start' | 'middle' | 'end' | 'insideStartTop' | 'insideStartBottom' | 'insideMiddleTop' | 'insideMiddleBottom' | 'insideEndTop' | 'insideEndBottom';
        formatter?: string;
    };
}

export interface MarkLineConfig {
    silent?: boolean;
    symbol?: string | [string, string];
    symbolSize?: number | [number, number];
    precision?: number;
    label?: {
        show?: boolean;
        position?: 'start' | 'middle' | 'end';
        formatter?: string;
    };
    lineStyle?: {
        color?: string;
        width?: number;
        type?: 'solid' | 'dashed' | 'dotted';
        opacity?: number;
    };
    emphasis?: {
        lineStyle?: {
            width?: number;
            type?: 'solid' | 'dashed' | 'dotted';
        };
        label?: {
            show?: boolean;
        };
    };
    data?: MarkLineItem[];
}

interface MarkLineConfigProps {
    config?: MarkLineConfig;
    onChange: (config: MarkLineConfig) => void;
}

/**
 * 标记线配置组件
 */
const MarkLineConfig: React.FC<MarkLineConfigProps> = ({ config = {}, onChange }) => {
    const [visible, setVisible] = useState(false);
    const [editingItem, setEditingItem] = useState<MarkLineItem | null>(null);
    const [editingIndex, setEditingIndex] = useState<number | null>(null);
    const [lineType, setLineType] = useState<'preset' | 'custom'>('preset');

    // 确保配置对象存在
    const markLineConfig: MarkLineConfig = config || {};
    const markLineData = markLineConfig.data || [];

    // 使用useOptimistic优化UI更新体验
    const [optimisticData, setOptimisticData] = useOptimistic(
        markLineData,
        (state, newData: MarkLineItem[]) => newData
    );

    // 初始化模态框数据
    const defaultModalItem: MarkLineItem = {
        name: '',
        lineStyle: {
            type: 'solid',
            width: 1
        },
        label: {
            show: true,
            position: 'middle'
        }
    };

    // 使用useState管理模态框状态（简化，避免多个Hooks报错）
    const [modalItem, setModalItem] = useState<MarkLineItem>(defaultModalItem);

    // 当打开模态框时初始化编辑项
    React.useEffect(() => {
        if (visible && editingItem) {
            setModalItem(editingItem);
        } else if (visible) {
            setModalItem(defaultModalItem);
        }
    }, [visible, editingItem]);

    // 处理配置更改
    const handleConfigChange = (key: string, value: any) => {
        // 处理嵌套属性
        if (key.includes('.')) {
            const keys = key.split('.');
            const updatedConfig = { ...markLineConfig };
            let current = updatedConfig as any;

            for (let i = 0; i < keys.length - 1; i++) {
                if (!current[keys[i]]) {
                    current[keys[i]] = {};
                }
                current = current[keys[i]];
            }

            current[keys[keys.length - 1]] = value;
            onChange(updatedConfig);
        } else {
            const updatedConfig = { ...markLineConfig, [key]: value };
            onChange(updatedConfig);
        }
    };

    // 添加或更新标记线 - 使用乐观更新
    const handleAddOrUpdateMarkLine = () => {
        const newData = [...(markLineData || [])];

        if (editingIndex !== null) {
            // 更新现有项目
            newData[editingIndex] = modalItem;
        } else {
            // 添加新项目
            newData.push(modalItem);
        }

        // 乐观更新UI
        setOptimisticData(newData);

        // 实际更新数据
        handleConfigChange('data', newData);
        setVisible(false);
        setEditingItem(null);
        setEditingIndex(null);
    };

    // 删除标记线 - 使用乐观更新
    const handleDeleteMarkLine = (index: number) => {
        const newData = [...markLineData];
        newData.splice(index, 1);

        // 乐观更新UI
        setOptimisticData(newData);

        // 实际更新数据
        handleConfigChange('data', newData);
    };

    // 编辑现有标记线
    const handleEditMarkLine = (item: MarkLineItem, index: number) => {
        setEditingItem(item);
        setEditingIndex(index);
        setLineType(item.type || (item.startPoint || item.endPoint) ? 'custom' : 'preset');
        setVisible(true);
    };

    // 更新模态框中的项目路径属性
    const updateNestedModalItem = (key: string, value: any) => {
        if (key.includes('.')) {
            const keys = key.split('.');
            const updatedItem = { ...modalItem };
            let current = updatedItem as any;

            for (let i = 0; i < keys.length - 1; i++) {
                if (!current[keys[i]]) {
                    current[keys[i]] = {};
                }
                current = current[keys[i]];
            }

            current[keys[keys.length - 1]] = value;
            setModalItem(updatedItem);
        } else {
            setModalItem({ ...modalItem, [key]: value });
        }
    };

    // 表单项标题组件
    const FormItemLabel = ({ children, tooltip }: { children: React.ReactNode, tooltip?: string }) => (
        <div style={{ marginBottom: 4, display: 'flex', alignItems: 'center' }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                {children}
            </Typography.Text>
            {tooltip && (
                <Tooltip title={tooltip}>
                    <InfoCircleOutlined style={{ marginLeft: 4, fontSize: 12, color: '#999' }} />
                </Tooltip>
            )}
        </div>
    );

    // 表格列定义
    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string) => text || '-'
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (text: string, record: MarkLineItem) => {
                if (text) {
                    const typeMap: Record<string, string> = {
                        'min': '最小值',
                        'max': '最大值',
                        'average': '平均值'
                    };
                    return typeMap[text] || '自定义';
                } else if (record.startPoint || record.endPoint) {
                    return '自定义坐标';
                }
                return '自定义';
            }
        },
        {
            title: '线条样式',
            key: 'lineStyle',
            render: (_: any, record: MarkLineItem) => {
                if (record.lineStyle?.type) {
                    const typeMap: Record<string, string> = {
                        'solid': '实线',
                        'dashed': '虚线',
                        'dotted': '点线'
                    };
                    return typeMap[record.lineStyle.type] || '实线';
                }
                return '实线';
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: MarkLineItem, index: number) => (
                <Space size="middle">
                    <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={() => handleEditMarkLine(record, index)}
                    />
                    <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteMarkLine(index)}
                    />
                </Space>
            )
        }
    ];

    // 标记线编辑模态框 - 重构为正常的JSX渲染，不再是函数
    const markLineModal = (
        <Modal
            title={editingIndex !== null ? "编辑标记线" : "添加标记线"}
            open={visible}
            onOk={handleAddOrUpdateMarkLine}
            onCancel={() => {
                setVisible(false);
                setEditingItem(null);
                setEditingIndex(null);
            }}
            width={600}
        >
            <div className="form-container">
                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记线显示的名称">
                            名称
                        </FormItemLabel>
                        <Input
                            value={modalItem.name}
                            onChange={e => updateNestedModalItem('name', e.target.value)}
                            placeholder="标记线名称"
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记线类型，选择预设类型或自定义">
                            类型设置
                        </FormItemLabel>
                        <Select
                            value={lineType}
                            onChange={value => {
                                setLineType(value);
                                if (value === 'preset') {
                                    // 清除自定义坐标
                                    const newItem = { ...modalItem };
                                    delete newItem.startPoint;
                                    delete newItem.endPoint;
                                    updateNestedModalItem('type', undefined);
                                } else {
                                    // 清除预设类型 - 修复类型错误
                                    const newItem = { ...modalItem };
                                    newItem.type = undefined; // 使用undefined而不是空字符串
                                    updateNestedModalItem('type', undefined);
                                }
                            }}
                            style={{ width: '100%' }}
                            options={[
                                { label: '预设类型', value: 'preset' },
                                { label: '自定义坐标', value: 'custom' }
                            ]}
                        />
                    </Col>

                    {lineType === 'preset' && (
                        <Col span={12}>
                            <FormItemLabel tooltip="预设标记线类型">
                                预设类型
                            </FormItemLabel>
                            <Select
                                value={modalItem.type || ''}
                                onChange={value => updateNestedModalItem('type', value)}
                                style={{ width: '100%' }}
                                options={[
                                    { label: '最大值', value: 'max' },
                                    { label: '最小值', value: 'min' },
                                    { label: '平均值', value: 'average' }
                                ]}
                            />
                        </Col>
                    )}

                    {lineType === 'custom' && (
                        <>
                            <Divider orientation="left">起点设置</Divider>
                            <Col span={12}>
                                <FormItemLabel tooltip="起点X坐标">
                                    起点X坐标
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.startPoint?.xAxis !== undefined ? Number(modalItem.startPoint.xAxis) : undefined}
                                    onChange={value => {
                                        const startPoint = modalItem.startPoint || {};
                                        updateNestedModalItem('startPoint', { ...startPoint, xAxis: value });
                                    }}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                            <Col span={12}>
                                <FormItemLabel tooltip="起点Y坐标">
                                    起点Y坐标
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.startPoint?.yAxis !== undefined ? Number(modalItem.startPoint.yAxis) : undefined}
                                    onChange={value => {
                                        const startPoint = modalItem.startPoint || {};
                                        updateNestedModalItem('startPoint', { ...startPoint, yAxis: value });
                                    }}
                                    style={{ width: '100%' }}
                                />
                            </Col>

                            <Divider orientation="left">终点设置</Divider>
                            <Col span={12}>
                                <FormItemLabel tooltip="终点X坐标">
                                    终点X坐标
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.endPoint?.xAxis !== undefined ? Number(modalItem.endPoint.xAxis) : undefined}
                                    onChange={value => {
                                        const endPoint = modalItem.endPoint || {};
                                        updateNestedModalItem('endPoint', { ...endPoint, xAxis: value });
                                    }}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                            <Col span={12}>
                                <FormItemLabel tooltip="终点Y坐标">
                                    终点Y坐标
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.endPoint?.yAxis !== undefined ? Number(modalItem.endPoint.yAxis) : undefined}
                                    onChange={value => {
                                        const endPoint = modalItem.endPoint || {};
                                        updateNestedModalItem('endPoint', { ...endPoint, yAxis: value });
                                    }}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                        </>
                    )}

                    <Divider orientation="left">线条样式</Divider>
                    <Col span={12}>
                        <FormItemLabel tooltip="线条样式">
                            线条类型
                        </FormItemLabel>
                        <Select
                            value={modalItem.lineStyle?.type || 'solid'}
                            onChange={value => {
                                const lineStyle = modalItem.lineStyle || {};
                                updateNestedModalItem('lineStyle', { ...lineStyle, type: value });
                            }}
                            style={{ width: '100%' }}
                            options={[
                                { label: '实线', value: 'solid' },
                                { label: '虚线', value: 'dashed' },
                                { label: '点线', value: 'dotted' }
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="线条宽度">
                            线条宽度
                        </FormItemLabel>
                        <InputNumber
                            value={modalItem.lineStyle?.width || 1}
                            onChange={value => {
                                const lineStyle = modalItem.lineStyle || {};
                                updateNestedModalItem('lineStyle', { ...lineStyle, width: value });
                            }}
                            min={1}
                            max={10}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="线条颜色">
                            线条颜色
                        </FormItemLabel>
                        <ColorPicker
                            value={modalItem.lineStyle?.color}
                            onChange={color => {
                                const lineStyle = modalItem.lineStyle || {};
                                updateNestedModalItem('lineStyle', { ...lineStyle, color: color.toHexString() });
                            }}
                            showText
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="线条透明度">
                            透明度
                        </FormItemLabel>
                        <InputNumber
                            value={modalItem.lineStyle?.opacity || 1}
                            onChange={value => {
                                const lineStyle = modalItem.lineStyle || {};
                                updateNestedModalItem('lineStyle', { ...lineStyle, opacity: value });
                            }}
                            min={0}
                            max={1}
                            step={0.1}
                            style={{ width: '100%' }}
                        />
                    </Col>

                    <Divider orientation="left">标签设置</Divider>
                    <Col span={12}>
                        <FormItemLabel tooltip="是否显示标签">
                            显示标签
                        </FormItemLabel>
                        <Switch
                            checked={modalItem.label?.show !== false}
                            onChange={checked => {
                                const label = modalItem.label || {};
                                updateNestedModalItem('label', { ...label, show: checked });
                            }}
                        />
                    </Col>
                    {modalItem.label?.show !== false && (
                        <Col span={12}>
                            <FormItemLabel tooltip="标签位置">
                                标签位置
                            </FormItemLabel>
                            <Select
                                value={modalItem.label?.position || 'middle'}
                                onChange={value => {
                                    const label = modalItem.label || { show: true };
                                    updateNestedModalItem('label', { ...label, position: value });
                                }}
                                style={{ width: '100%' }}
                                options={[
                                    { label: '起点', value: 'start' },
                                    { label: '中间', value: 'middle' },
                                    { label: '终点', value: 'end' }
                                ]}
                            />
                        </Col>
                    )}
                </Row>
            </div>
        </Modal>
    );

    return (
        <div>
            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Title level={5} style={{ margin: 0 }}>
                    标记线设置
                    <Tooltip title="在图表上添加辅助线，如平均线、最大值线、趋势线等">
                        <InfoCircleOutlined style={{ fontSize: 14, marginLeft: 8 }} />
                    </Tooltip>
                </Typography.Title>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => {
                        setEditingItem(null);
                        setEditingIndex(null);
                        setLineType('preset');
                        setVisible(true);
                    }}
                >
                    添加标记线
                </Button>
            </div>

            {/* 标记线列表 */}
            <Table
                columns={columns}
                dataSource={optimisticData.map((item, index) => ({ ...item, key: index }))}
                size="small"
                pagination={false}
                style={{ marginBottom: 16 }}
            />

            {/* 全局标记线样式设置 */}
            <Divider orientation="left">全局样式设置</Divider>
            <div className="form-container">
                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <FormItemLabel tooltip="是否响应鼠标事件">
                            交互响应
                        </FormItemLabel>
                        <Switch
                            checked={!markLineConfig.silent}
                            onChange={checked => handleConfigChange('silent', !checked)}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记线默认线条样式">
                            默认线型
                        </FormItemLabel>
                        <Select
                            value={markLineConfig.lineStyle?.type || 'solid'}
                            onChange={value => handleConfigChange('lineStyle.type', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '实线', value: 'solid' },
                                { label: '虚线', value: 'dashed' },
                                { label: '点线', value: 'dotted' }
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记线默认宽度">
                            默认宽度
                        </FormItemLabel>
                        <InputNumber
                            value={markLineConfig.lineStyle?.width || 1}
                            onChange={value => handleConfigChange('lineStyle.width', value)}
                            min={1}
                            max={10}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记线默认颜色">
                            默认颜色
                        </FormItemLabel>
                        <ColorPicker
                            value={markLineConfig.lineStyle?.color}
                            onChange={color => handleConfigChange('lineStyle.color', color.toHexString())}
                            showText
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="数值精度，保留的小数位数">
                            数值精度
                        </FormItemLabel>
                        <InputNumber
                            value={markLineConfig.precision || 2}
                            onChange={value => handleConfigChange('precision', value)}
                            min={0}
                            max={10}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="高亮时的线条宽度">
                            高亮线宽
                        </FormItemLabel>
                        <InputNumber
                            value={markLineConfig.emphasis?.lineStyle?.width || 2}
                            onChange={value => handleConfigChange('emphasis.lineStyle.width', value)}
                            min={1}
                            max={10}
                            style={{ width: '100%' }}
                        />
                    </Col>
                </Row>
            </div>

            {/* 直接渲染模态框，不再通过函数调用 */}
            {markLineModal}
        </div>
    );
};

export default MarkLineConfig;